package com.xiaoshuidi.cloud.module.iot.uitils;

import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <br>
 *
 * @author Porter
 * create by 2019/3/20
 * @Emial Porter.Wang@ixiaoshuidi.com
 */
public class PasswordUtils {

    public static void main(String[] args) {
        String password = "iiiiiiiiiiiiiiiiiio";
        if (true == isValid(password)) {
            System.out.println("合法密码格式");
        } else {
            System.out.println("不合法密码格式");
        }
    }

    public static boolean isValid(String password) {

        if (password.length() > 0) {
            if (password.length() < 6 || password.length() > 18) {
                System.out.println("密码长度为6-18位");
                return false;
            }
            //判断是否有空格字符串
            for (int t = 0; t < password.length(); t++) {
                String b = password.substring(t, t + 1);
                if (b.equals(" ")) {
                    System.out.println("有空字符串");
                    return false;
                }
            }
            //判断是否有汉字
            int count = 0;
            String regEx = "[\\u4e00-\\u9fa5]";
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(password);
            while (m.find()) {
                for (int i = 0; i <= m.groupCount(); i++) {
                    count = count + 1;
                }
            }
            if (count > 0) {
                System.out.println("有汉字");
                return false;
            }


            //判断是否是字母和数字
            int numberCounter = 0;
            for (int i = 0; i < password.length(); i++) {
                char c = password.charAt(i);
                if (!Character.isLetterOrDigit(c)) {
                    return false;
                }
                if (Character.isDigit(c)) {
                    numberCounter++;
                }
            }

        } else {
            return false;
        }
        return true;
    }

    /**
     * 根据长度随机生成数字密码
     *
     * @param length 长度
     * @return
     */
    public static String getRandomPassword(int length) {
        String password = "";
        Random random = new Random();
        for (int i = 0; i < length; i++) {
            password += random.nextInt(10);
        }
        return password;
    }

}


